import { useState } from "react";
import Taro from "@tarojs/taro";
import { Input, View } from "@tarojs/components";

import ByIcon from "./ByIcon";

type BySearchBarProps = {
  placeholder?: string;
  className?: string;
  disabled?: boolean;
  height?: string;
  circle?: boolean;
};

type BySearchBarEvents = {
  onClear?: (undefined) => void;
  onConfirm?: (value: string) => void;
  onInput?: (e: string) => string | undefined | void;
};
export default ({
  placeholder,
  className,
  disabled,
  height,
  circle,

  onClear,
  onInput,
  onConfirm,
}: BySearchBarProps & BySearchBarEvents) => {
  // 胶囊几何信息
  height = height
    ? height
    : Taro.getMenuButtonBoundingClientRect().height + "px";

  const [value, setValue] = useState<string>();

  const hanldeInput = ({ detail }) => {
    const val = detail.value;
    const res = onInput ? onInput(val) : val;
    setValue(res);
  };

  const handleClear = () => {
    setValue("");
    onClear?.(undefined);
  };

  return (
    <View
      className={`flex items-center bg-page px-3  ${
        circle ? "rounded-full" : "rounded-lg"
      } ${className}`}
    >
      <ByIcon name="Search" size={36} />

      <Input
        value={value}
        disabled={disabled}
        confirmType="search"
        className={`ml-3 flex-auto`}
        placeholder={placeholder}
        onConfirm={() => onConfirm?.(value || "")}
        onInput={hanldeInput}
        style={{ height }}
      />

      {value && (
        <ByIcon
          name="CloseCircle"
          size={32}
          className="ml-2 text-second"
          onClick={handleClear}
        />
      )}
    </View>
  );
};
